﻿@using System.IO.Compression
@using Tool.Utils


<MudDialog>
    <TitleContent>
        查看EVD
    </TitleContent>
    <DialogContent>
        <MudCarousel Class="mud-width-full" ItemsSource="@_pdfs" Style="height:500px;" ShowArrows="@arrows" ShowBullets="@bullets" EnableSwipeGesture="@enableSwipeGesture" AutoCycle="@autocycle" TData="object">
            <ItemTemplate>
                <div class="d-flex flex-column flex-column justify-center" style="height:100%">
                    <object data="@context" type="application/pdf" width="100%" height="100%">
                        <p>无法加载 PDF 文件，请下载 <a href="@context">下载 PDF</a></p>
                    </object>
                    <MudSpacer></MudSpacer>
                    <MudText Align="@Align.Center" Class="mx-auto">@context</MudText>
                </div>
            </ItemTemplate>

        </MudCarousel>
    </DialogContent>
    <DialogActions>
        <MudButton Color="Color.Primary" OnClick="Submit">关闭</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter]
    private IMudDialogInstance MudDialog { get; set; }

    [Parameter]
    public string EvdUrl { get; set; }
    [Parameter]
    public string SelectedSite { get; set; }

    [Parameter]
    public string GroupName { get; set; }

    private void Submit() => MudDialog.Close(DialogResult.Ok(true));


    private bool arrows = true;
    private bool bullets = true;
    private bool enableSwipeGesture = true;
    private bool autocycle = true;
    private Transition transition = Transition.Slide;

    private List<string> _pdfs = new List<string>();

    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();
        bool isStartWithHttp = EvdUrl.StartsWith("http");
        // 下载文件
        // 1. 提取 fileId (去掉第一个 '/' 之前的部分)
        string fileId = string.Empty;
        if (isStartWithHttp)
        {
            fileId = EvdUrl.Substring(EvdUrl.IndexOf("/group") + 1);
        }
        else
        {
            fileId = EvdUrl.Substring(EvdUrl.IndexOf("/") + 1);
        }

        // 2. 获取当前时间戳 (秒)
        int ts = (int)(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

        // 3. 生成 token
        string token = FileHelper.GetToken(fileId, ts, "SFqdFASTDFS#@!$%^");

        // 4. 构造带参数的 URL
        string queryString = $"token={token}&ts={ts}";
        string fullFileUrl = $"{EvdUrl}?{queryString}";

        // 5. 构造完整的下载 URL
        // 注意：原始 Java 代码中 URL 后面有空格，这里已修正

        string completeUrl = string.Empty;
        if (!isStartWithHttp)
        {
            completeUrl = $"{FileHelper.GetFileHost(SelectedSite, GroupName)}/{fullFileUrl}";
        }
        else
        {
            completeUrl = fullFileUrl;
        }
        byte[] bytes = await HttpUtil.DownloadBytesAsync(completeUrl);
        var extractPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "extracted");
        if (!Directory.Exists(extractPath))
            Directory.CreateDirectory(extractPath);
        else
        {
            FolderHelper.ClearFolder(extractPath);
        }
        try
        {
            using MemoryStream zipStream = new MemoryStream(bytes);
            ZipFile.ExtractToDirectory(zipStream, extractPath, overwriteFiles: true);
            var dirs = Directory.EnumerateDirectories(extractPath).ToList();
            var tmp = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "extracted", "tmp");
            if (!Directory.Exists(tmp))
            {
                Directory.CreateDirectory(tmp);
            }
            foreach (var dir in dirs)
            {
                foreach (var file in Directory.EnumerateFiles(dir))
                {
                    // if (Path.GetExtension(file) == ".ofd")
                    // {
                    //     var ofd = new OFDDocument(file);
                        
                    //     ofd.Save();
                    // }
                    System.IO.File.Copy(file, Path.Combine(tmp, Path.GetFileName(file)), true);
                }
            }
            var tmpFiles = Directory.EnumerateFiles(tmp);
            _pdfs = tmpFiles.OrderBy(p => p).Select(p => $"extracted/tmp/{Path.GetFileName(p)}").ToList();
        }
        catch (Exception ex)
        {

        }

    }
    // protected override async Task OnInitializedAsync()
    // {

    // }
}


